<?php
/**
 * erp日销量报表 (erp)
 */
namespace App\Logic\SalesReport;

use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductAmazonSkuCCS;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductRakutenSkuCCS;
use App\Models\Product\ProductSku;
use App\Models\SalesAmazon\SalesVolumeDay;
use App\Models\SalesReport\DailyVolume;
use Illuminate\Support\Facades\DB;
class DailySaleVolume{

    /**
     * 日销量统计报表(erp)
     * @param int $days
     */
    public static function initSalesVolume($days = 1){

        $i = 1;
        while(true) {
            if ($i > $days) break;
            $date = date('Y-m-d',strtotime("-{$i} days"));
            $day = date('Ymd',strtotime("-{$i} days"));

            try{
                DB::beginTransaction();
                DailyVolume::query()->where('report_date',$date)->update(['volume' => 0]);
                $areaArr = [];
                $classifyArr = [];
                $seasonArr = [];
                $sellerArr = [];

                //平台基础日销量
                SalesVolumeDay::query()
                    ->where('day', $day)
                    ->select('plat_id','country_id','psku_id', DB::raw('sum(`volume`) as volume'))
                    ->groupBy('plat_id','country_id','psku_id')
                    ->chunk(500, function ($items) use(&$areaArr,&$classifyArr,&$seasonArr,&$sellerArr,$date){
                        foreach ($items as $item){
                            $countryId = $item->country_id;
                            if(!array_key_exists($countryId,$areaArr)){
                                $areaArr[$countryId] = SysICountry::getAreaIdByCountryId($countryId);
                            }
                            $areaId = $areaArr[$countryId];

                            if(!array_key_exists($item->psku_id,$classifyArr)){
                                if(!$item->psku_id){
                                    $classifyArr[$item->psku_id] = 0;
                                }else{
                                    $classifyArr[$item->psku_id] = ProductSku::getValueById($item->psku_id, 'classify_id');
                                }
                            }
                            $classifyId = $classifyArr[$item->psku_id];

                            if(!array_key_exists($classifyId,$seasonArr)){
                                if(!$classifyId){
                                    $seasonArr[$classifyId] = 0;
                                }else{
                                    $seasonArr[$classifyId] = ProductClassify::getSeasonById($classifyId);
                                }
                            }
                            $season = $seasonArr[$classifyId];

                            $sellerKey = $item->plat_id.'_'.$countryId.'_'.$classifyId;
                            if(!array_key_exists($sellerKey,$sellerArr)){
                                if($item->plat_id == SysPlat::PLAT_AMAZON) { //amazon
                                    $_sellerId = ProductAmazonSkuCCS::getSellerId($countryId, $classifyId);
                                }elseif($item->plat_id == SysPlat::PLAT_SHOPIFY){  //shopify
                                    $_sellerId = 33;
                                }elseif($item->plat_id == SysPlat::PLAT_RAKUTEN){  //rakuten
                                    $_sellerId = 124;
                                }else{
                                    $_sellerId = 0;
                                }
                                $sellerArr[$sellerKey] = $_sellerId ?: 0;
                            }
                            $sellerId = $sellerArr[$sellerKey];

                            //erp基础日销量
                            DailyVolume::query()->updateOrCreate([
                                'report_date' => $date,
                                'plat_id'     => $item->plat_id,
                                'country_id'  => $countryId,
                                'psku_id'     => $item->psku_id,
                            ],[
                                'area_id'     => $areaId,
                                'seller_id'   => $sellerId,
                                'classify_id' => $classifyId,
                                'season'      => $season,
                                'volume'      => $item->volume,
                            ]);
                        }
                    });

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }

            echo $date.PHP_EOL;
            $i++;
            sleep(1);
        }
    }

    /**
     * 补平台数据
     * @param $startDate
     * @param $endDate
     * @return false
     */
    public static function initSalesVolumeBack($startDate,$endDate){

        $shopifyPlat = SysPlat::PLAT_SHOPIFY;

        $startDates = $startDate == 'null' ? date('Y-m-d', strtotime("-1 days")) : $startDate; //开始时间
        $endDates = $endDate == 'null' ? date('Y-m-d', strtotime("-1 days")) : $endDate; //结束时间
        if (!strtotime($startDates) || !strtotime($endDates)) return false;

        $bof = strtotime($startDates); //开始
        $eof = strtotime($endDates); //结束
        while(true) {
            if ($bof > $eof) break;
            $time = $bof;
            $date = date('Y-m-d',$time);
            $day = date('Ymd',$time);

            try{
                DB::beginTransaction();
                DailyVolume::query()->where('plat_id', $shopifyPlat)->where('report_date',$date)->update(['volume' => 0]);
                $areaArr = [];
                $classifyArr = [];
                $seasonArr = [];
                $sellerArr = [];

                //平台基础日销量
                SalesVolumeDay::query()
                    ->where('day', $day)
                    ->where('plat_id', $shopifyPlat)
                    ->select('plat_id','country_id','psku_id', DB::raw('sum(`volume`) as volume'))
                    ->groupBy('plat_id','country_id','psku_id')
                    ->chunk(500, function ($items) use(&$areaArr,&$classifyArr,&$seasonArr,&$sellerArr,$date){
                        foreach ($items as $item){
                            $countryId = $item->country_id;
                            if(!array_key_exists($countryId,$areaArr)){
                                $areaArr[$countryId] = SysICountry::getAreaIdByCountryId($countryId);
                            }
                            $areaId = $areaArr[$countryId];

                            if(!array_key_exists($item->psku_id,$classifyArr)){
                                if(!$item->psku_id){
                                    $classifyArr[$item->psku_id] = 0;
                                }else{
                                    $classifyArr[$item->psku_id] = ProductSku::getValueById($item->psku_id, 'classify_id');
                                }
                            }
                            $classifyId = $classifyArr[$item->psku_id];

                            if(!array_key_exists($classifyId,$seasonArr)){
                                if(!$classifyId){
                                    $seasonArr[$classifyId] = 0;
                                }else{
                                    $seasonArr[$classifyId] = ProductClassify::getSeasonById($classifyId);
                                }
                            }
                            $season = $seasonArr[$classifyId];

                            $sellerId = 33;

                            //erp基础日销量
                            DailyVolume::query()->updateOrCreate([
                                'report_date' => $date,
                                'plat_id'     => $item->plat_id,
                                'country_id'  => $countryId,
                                'psku_id'     => $item->psku_id,
                            ],[
                                'area_id'     => $areaId,
                                'seller_id'   => $sellerId,
                                'classify_id' => $classifyId,
                                'season'      => $season,
                                'volume'      => $item->volume,
                            ]);
                        }
                    });

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }

            echo $day.PHP_EOL;
            $bof += 60*60*24;

            sleep(2);
        }
    }

}
